package com.senney.bio;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author lanmengye@outlook.com
 * @Date 2020/12/28 22:23
 */
public class BIOServer {
    public static void main(String[] args) throws Exception {
        ExecutorService threadPool = Executors.newCachedThreadPool();

        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动……");

        while (true) {
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端[" + socket.getRemoteSocketAddress() + "]");
            threadPool.execute(() -> handle(socket));
        }
    }

    public static void handle(Socket socket) {
        System.out.println("线程信息：id = " + Thread.currentThread().getId()
                + ", name = " + Thread.currentThread().getName());
        byte[] bytes = new byte[1024];
        try {
            InputStream inputStream = socket.getInputStream();
            int len;
            while ((len = inputStream.read(bytes)) != -1) {
                System.out.println(new String(bytes, 0, len));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭和客户端[" + socket.getRemoteSocketAddress() + "]的连接");
            try {
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
